package buildGraph;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class AdjMertic {
    private int vertexNum;
    private int edgeNum;
    private int[][] adj;

    public AdjMertic(String fileName) {
        File file = new File(fileName);
        try (Scanner scanner = new Scanner(file)) {
            vertexNum = scanner.nextInt();
            if (vertexNum < 0) {
                throw new IllegalArgumentException("vertex number must be non-negative");
            }
            adj = new int[vertexNum][vertexNum];
            edgeNum = scanner.nextInt();
            if (edgeNum < 0) {
                throw new IllegalArgumentException("edge number must be non-negative");
            }
            for (int i = 0; i < edgeNum; i++) {
                int a = scanner.nextInt();
                validateVertex(a);
                int b = scanner.nextInt();
                validateVertex(b);
                if (a == b) {
                    throw new IllegalArgumentException("Self Loop is Detected!");
                }
                if (adj[a][b] == 1) {
                    throw new IllegalArgumentException("Parallel Edges are Detected!");
                }
                adj[a][b] = 1;
                adj[b][a] = 1;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void validateVertex(int vertexNum) {
        if (vertexNum < 0 || vertexNum >= this.vertexNum) {
            throw new IllegalArgumentException("vertex " + vertexNum + "is invalid.");
        }
    }

    public int getVertexNum() {
        return vertexNum;
    }

    public int getEdgeNum() {
        return edgeNum;
    }

    public boolean hasEdge(int v, int w) {
        validateVertex(v);
        validateVertex(w);
        return adj[v][w] == 1;
    }

    public List<Integer> adj(int v) {
        validateVertex(v);
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < this.vertexNum; i++) {
            if (adj[v][i] == 1) {
                res.add(i);
            }
        }
        return res;
    }

    public int degree(int v) {
        return adj(v).size();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("V = %d, E = %d", vertexNum, edgeNum)).append("\n");
        for (int i = 0; i < vertexNum; i++) {
            for (int j = 0; j < vertexNum; j++) {
                sb.append(String.format("%d ", adj[i][j]));
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    public static void main(String[] a) {
        AdjMertic adjMertic = new AdjMertic("Olag.txt");
        System.out.println(adjMertic);
    }
}
